﻿var DataSourceTree = function(options) {
    this._data = options.data;
    this._delay = options.delay;
};

DataSourceTree.prototype.data = function (options, callback) {
    var $data = null;

    if (!("name" in options) && !("type" in options)) {
        $data = this._data;//the root tree
        callback({ data: $data });
        return;
    }
    else if ("type" in options && options.type == "folder") {
        if ("additionalParameters" in options && "children" in options.additionalParameters)
            $data = options.additionalParameters.children;
        else $data = { };//no data
    }

    if ($data != null)//this setTimeout is only for mimicking some random delay
        setTimeout(function () { callback({ data: $data }); }, parseInt(Math.random() * 500) + 200);

    //we have used static data here
    //but you can retrieve your data dynamically from a server using ajax call
    //checkout examples/treeview.html and examples/treeview.js for more info
};

function levelFormatter1(cellvalue, options, rowObject) {

    var retVal = cellvalue;
    $.each(globalLevels, function (index) {
        if (globalLevels[index].LevelId == cellvalue) {
            retVal = globalLevels[index].Name;
        }
    });
    if (retVal === null || retVal === 0) retVal = '';
    return retVal;
}

function nextPage(el) {
    var totalPage = parseInt($("#hTotalPage").val());
    if (parseInt($(".pagination li a.page-num:last-child").html()) >= totalPage) return;
    $(".pagination li:first-child").removeClass("disabled");

    var lastPage = 0;
    $.each($(".pagination li a.page-num"), function (i) {
        var oldValue = parseInt($(this).html());
        var newValue = oldValue + 1;
        lastPage = newValue;
        $(this).html(newValue);
    });
    if (lastPage >= totalPage) {
        $(".pagination li:last-child").addClass("disabled");
    }
}
function prevPage(el) {
    if ($(".pagination li a.page-num:first-child").html() == "1") return;
    $(".pagination li:last-child").removeClass("disabled");
    $.each($(".pagination li a.page-num"), function (i) {
        var oldValue = parseInt($(this).html());
        var newValue = oldValue - 1;
        if (newValue == 1) $(".pagination li:first-child").addClass("disabled");
        $(this).html(newValue);
    });

}
function buildPager(from, to) {
    var totalPage = parseInt($("#hTotalPage").val());

    if (from == 1)
        $(".pagination").append("<li class='disabled'><a href='javascript:void(0);' onclick='javascript:prevPage(this);'><i class='icon-double-angle-left'></i></a>");
    else
        $(".pagination").append("<li><a href='javascript:void(0);' onclick='javascript:prevPage(this);'><i class='icon-double-angle-left'></i></a>");

    for (i = from; i <= to; i++) {
        $(".pagination").append("<li><a class='page-num' href='javascript:void(0);' onclick='javascript:reloadPage(this);'>" + i + "</li>");
    }

    if (to < totalPage)
        $(".pagination").append("<li><a href='javascript:void(0);' onclick='javascript:nextPage(this);'><i class='icon-double-angle-right'></i></a>");
    else
        $(".pagination").append("<li><a class='disabled' href='javascript:void(0);' onclick='javascript:nextPage(this);'><i class='icon-double-angle-right'></i></a>");
}


var globallistlocation;
function bindlistLocation() {
    if (globallistlocation == null) {
        $.getJSON('/admin/api/location/get').done(function (locations) {
            globallistlocation = locations;

        });
    }
}
function locationFmatter(cellvalue, options, rowObject) {
    
    var retVal = cellvalue;
    $.each(globallistlocation, function (index) {
        if (globallistlocation[index].LocationId == cellvalue) {            
            retVal = globallistlocation[index].Name;
        }
    });
    if (retVal === null) retVal = '';
    return retVal;
}
function unformatlocation(cellvalue, options) {
    $.each(globallistlocation, function (index) {
        if (globallistlocation[index].Name == cellvalue) {
            return globallistlocation[index].LocationId;
        }
    });
    
    return cellvalue;
}

function jqGridLocationDropVal(elem, operation, value) {
    
    if (operation === 'get') {
        var id = $(elem).attr("id");
        return $("#" + id + " option:selected").val();

    } else if (operation === 'set') {

    }
};
function jqGridLocationDropEl(value, options) {
    var retVal = $(document.createElement('select'));
    //retval.innerHTML = "<option value='1'>HN</option>";
    $(retVal).addClass("form-control");

    $.each(globallistlocation, function (index) {
        if (globallistlocation[index].Name == value) {
            $(retVal).append("<option selected value='" + globallistlocation[index].LocationId + "'>" + globallistlocation[index].Name + "</option>");
        } else {
            $(retVal).append("<option value='" + globallistlocation[index].LocationId + "'>" + globallistlocation[index].Name + "</option>");
        }
    });
    //});
    return retVal;
}
function style_edit_form(form) {
    //enable datepicker on "sdate" field and switches for "stock" field
    form.find('input[name=sdate]').datepicker({ format: 'dd/mm/yyyy', autoclose: true })
        .end().find('input[name=stock]')
              .addClass('ace ace-switch ace-switch-5').wrap('<label class="inline" />').after('<span class="lbl"></span>');

    //update buttons classes
    var buttons = form.next().find('.EditButton .fm-button');
    buttons.addClass('btn btn-sm').find('[class*="-icon"]').remove();//ui-icon, s-icon
    buttons.eq(0).addClass('btn-primary').prepend('<i class="icon-ok"></i>');
    buttons.eq(1).prepend('<i class="icon-remove"></i>');

    buttons = form.next().find('.navButton a');
    buttons.find('.ui-icon').remove();
    buttons.eq(0).append('<i class="icon-chevron-left"></i>');
    buttons.eq(1).append('<i class="icon-chevron-right"></i>');
}

function style_delete_form(form) {
    var buttons = form.next().find('.EditButton .fm-button');
    buttons.addClass('btn btn-sm').find('[class*="-icon"]').remove();//ui-icon, s-icon
    buttons.eq(0).addClass('btn-danger').prepend('<i class="icon-trash"></i>');
    buttons.eq(1).prepend('<i class="icon-remove"></i>');
}

function style_search_filters(form) {
    form.find('.delete-rule').val('X');
    form.find('.add-rule').addClass('btn btn-xs btn-primary');
    form.find('.add-group').addClass('btn btn-xs btn-success');
    form.find('.delete-group').addClass('btn btn-xs btn-danger');
}
function style_search_form(form) {
    var dialog = form.closest('.ui-jqdialog');
    var buttons = dialog.find('.EditTable');
    buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'icon-retweet');
    buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'icon-comment-alt');
    buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'icon-search');
}

function beforeDeleteCallback(e) {
    var form = $(e[0]);
    if (form.data('styled')) return false;

    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');
    style_delete_form(form);

    form.data('styled', true);
}

function beforeEditCallback(e) {
    var form = $(e[0]);
    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');
    style_edit_form(form);
}


//it causes some flicker when reloading or navigating grid
//it may be possible to have some custom formatter to do this as the grid is being created to prevent this
//or go back to default browser checkbox styles for the grid
function styleCheckbox(table) {
    /**
        $(table).find('input:checkbox').addClass('ace')
        .wrap('<label />')
        .after('<span class="lbl align-top" />')


        $('.ui-jqgrid-labels th[id*="_cb"]:first-child')
        .find('input.cbox[type=checkbox]').addClass('ace')
        .wrap('<label />').after('<span class="lbl align-top" />');
    */
}


//unlike navButtons icons, action icons in rows seem to be hard-coded
//you can change them like this in here if you want
function updateActionIcons(table) {
    /**
    var replacement = 
    {
        'ui-icon-pencil' : 'icon-pencil blue',
        'ui-icon-trash' : 'icon-trash red',
        'ui-icon-disk' : 'icon-ok green',
        'ui-icon-cancel' : 'icon-remove red'
    };
    $(table).find('.ui-pg-div span.ui-icon').each(function(){
        var icon = $(this);
        var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
        if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
    })
    */
}

//replace icons with FontAwesome icons like above
function updatePagerIcons(table) {
    var replacement =
    {
        'ui-icon-seek-first': 'icon-double-angle-left bigger-140',
        'ui-icon-seek-prev': 'icon-angle-left bigger-140',
        'ui-icon-seek-next': 'icon-angle-right bigger-140',
        'ui-icon-seek-end': 'icon-double-angle-right bigger-140'
    };
    $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function() {
        var icon = $(this);
        var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

        if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
    });
}

function enableTooltips(table) {
    $('.navtable .ui-pg-button').tooltip({ container: 'body' });
    $(table).find('.ui-pg-div').tooltip({ container: 'body' });
}

//enable search/filter toolbar
//jQuery(grid_selector).jqGrid('filterToolbar',{defaultSearch:true,stringResult:true})

//switch element when editing inline
function aceSwitch(cellvalue, options, cell) {
    setTimeout(function () {
        $(cell).find('input[type=checkbox]')
                .wrap('<label class="inline" />')
            .addClass('ace ace-switch ace-switch-5')
            .after('<span class="lbl"></span>');
    }, 0);
}
//enable datepicker
function pickDate(cellvalue, options, cell) {
    setTimeout(function () {
        $(cell).find('input[type=text]')
                .datepicker({ format: 'dd/mm/yyyy', autoclose: true });
    }, 0);
}

function setupGridTable(grid_selector, pager_selector, searchUrl, editUrl, idFieldName, title, columnNames, columnModel, method, numRow, height) {
    var frmMethod = 'GET';
    if (method && method.length > 0) frmMethod = method;
    var $path_base = "/";
    jQuery(grid_selector).jqGrid({
        url: $path_base + searchUrl,
        datatype: "json",
        jsonReader: {
            root: "Rows",
            page: "Page",
            total: "Total",
            records: "Records",
            repeatitems: false,
            userdata: "UserData",
        },
        
        sortable: false,
        mtype: frmMethod,
        height: height,
        colNames: columnNames,
        colModel: columnModel,
        viewrecords: true,
        rowNum: numRow,
        rownumbers: true,
        rownumWidth: 40,
        rowList: [10, 20, 30],
        pager: pager_selector,
        altRows: true,
        multiselect: false,
        multiboxonly: false,

        loadComplete: function () {
            var table = this;
            var $grid = $(this);
            try {
                var caption = '';
                var tmp = parseInt($grid.jqGrid().getGridParam('userData'));
                if (isNaN(tmp)) {
                    var items = $grid.jqGrid().getGridParam('userData');
                    if (items != null && items.length > 0) {
                        for (var i = 0; i < items.length; i++) {
                            caption += i == 0 ? items[i] : ' - ' + items[i];
                        }
                    }
                }
                else {
                    caption = $.isNumeric(tmp) ? tmp : 0;
                }
                if (caption == '')
                    $grid.jqGrid('setCaption', title);
                else 
                    $grid.jqGrid('setCaption', title + ' (' + caption + ')');
            } catch (err) {
            }

            $('#grid-table_rn').html('STT');
            setTimeout(function () {
                styleCheckbox(table);

                updateActionIcons(table);
                updatePagerIcons(table);
                enableTooltips(table);

                $('#grid-table_rn').html('STT');
                $('#grid-table_rn').html('STT');
                $('#grid-table_rn').html('STT');
                $('#grid-table_rn').html('STT');
                $('#grid-table_rn').html('STT');
                $('#grid-table_rn').html('STT');
            }, 0);
            
            var rows = $grid.getDataIDs();
            for (var i = 0; i < rows.length; i++) {
                var status = $grid.getCell(rows[i], "CallType");
                if (status == 2) {
                    //$grid.jqGrid('setRowData', rows[i], false, { color: 'white', weightfont: 'bold', background: 'red' });
                    $grid.setCell(rows[i], 0, '', { background: 'YellowGreen' });
                }
            }
        },
        beforeRequest: function () {
            $('#grid-table_rn').html('STT');
        },
        gridComplete: function () {
            var grid = this;

            $('td[rowspan="1"]', grid).each(function () {
                var spans = $('td[rowspanid="' + this.id + '"]', grid).length + 1;

                if (spans > 1) {
                    $(this).attr('rowspan', spans);
                }
            });
        },
        editurl: $path_base + editUrl,//nothing is saved
        caption: title,
        autowidth: true
    });
}

function setupGridPager(grid_selector, pager_selector, searchUrl, editUrl, idFieldName, title, columnNames, columnModel, method) {
    //navButtons
    jQuery(grid_selector).jqGrid('navGrid', pager_selector,
        {
//navbar options
            edit: true,
            editicon: 'icon-pencil blue',
            add: true,
            addicon: 'icon-plus-sign purple',
            del: false,
            delicon: 'icon-trash red',
            search: false,
            searchicon: 'icon-search orange',
            refresh: true,
            refreshicon: 'icon-refresh green',
            view: false,
            viewicon: 'icon-zoom-in grey',
        },
        {
            //edit record form
            closeAfterEdit: false,
            recreateForm: true,
            beforeShowForm: function(e) {
                var form = $(e[0]);;
                form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');
                style_edit_form(form);
            },
            afterSubmit: function (response) {
                if (response != null) {
                    var text = response.responseText.replaceAll('/', '');
                    if (text.length > 0) {
                        $("#alert").addClass("alert alert-block alert-success");
                        $("#alert").html(text);
                    }
                }
                return [true];
            }
        },
        {
            //new record form
            closeAfterAdd: true,
            recreateForm: true,
            viewPagerButtons: false,
            beforeShowForm: function(e) {
                var form = $(e[0]);
                form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');
                style_edit_form(form);
            },
            afterSubmit: function(response) {
                if (response != null) {
                    var text = response.responseText.replaceAll('/', '');
                    if (text.length > 0) {
                        $("#alert").addClass("alert alert-block alert-success");
                        $("#alert").html(text);
                    }
                }
                return [true];
            }
        },
        {
            //delete record form
            recreateForm: true,
            beforeShowForm: function(e) {
                var form = $(e[0]);
                if (form.data('styled')) return false;

                form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');
                style_delete_form(form);

                form.data('styled', true);
            },
            onClick: function(e) {
            }
        },
        {
            //search form
            recreateForm: true,
            afterShowSearch: function(e) {
                var form = $(e[0]);
                form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />');
                style_search_form(form);
            },
            afterRedraw: function() {
                style_search_filters($(this));
            },
            multipleSearch: true,
            /**
            multipleGroup:true,
            showQuery: true
            */
        },
        {
            //view record form
            recreateForm: true,
            beforeShowForm: function(e) {
                var form = $(e[0]);
                form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />');
            }
        }
    );
}
function setupGridPagerWithoutEdit(grid_selector, pager_selector, searchUrl, editUrl, idFieldName, title, columnNames, columnModel, method) {
    //navButtons
    jQuery(grid_selector).jqGrid('navGrid', pager_selector,
        {
//navbar options
            edit: false,
            editicon: 'icon-pencil blue',
            add: false,
            addicon: 'icon-plus-sign purple',
            del: false,
            delicon: 'icon-trash red',
            search: false,
            searchicon: 'icon-search orange',
            refresh: false,
            refreshicon: 'icon-refresh green',
            view: false,
            viewicon: 'icon-zoom-in grey',
        },
        {
            //edit record form
            closeAfterEdit: false,
            recreateForm: true,
            beforeShowForm: function(e) {
                var form = $(e[0]);
                form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');
                style_edit_form(form);
            },
        },
        {
            //new record form
            closeAfterAdd: true,
            recreateForm: true,
            viewPagerButtons: false,
            beforeShowForm: function(e) {
                var form = $(e[0]);
                form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');
                style_edit_form(form);
            }
        },
        {
            //delete record form
            recreateForm: true,
            beforeShowForm: function(e) {
                var form = $(e[0]);
                if (form.data('styled')) return false;

                form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');
                style_delete_form(form);

                form.data('styled', true);
            },
            onClick: function(e) {
            }
        },
        {
            //search form
            recreateForm: true,
            afterShowSearch: function(e) {
                var form = $(e[0]);
                form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />');
                style_search_form(form);
            },
            afterRedraw: function() {
                style_search_filters($(this));
            },
            multipleSearch: true,
            /**
            multipleGroup:true,
            showQuery: true
            */
        },
        {
            //view record form
            recreateForm: true,
            beforeShowForm: function(e) {
                var form = $(e[0]);
                form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />');
            }
        }
    );
}

function setupGrid(grid_selector, pager_selector, searchUrl, editUrl, idFieldName, title, columnNames, columnModel, method) {
    setupGridTable(grid_selector, pager_selector, searchUrl, editUrl, idFieldName, title, columnNames, columnModel, method, 30, '350px');
    setupGridPager(grid_selector, pager_selector, searchUrl, editUrl, idFieldName, title, columnNames, columnModel, method);
};
function setupGridWithoutEdit(grid_selector, pager_selector, searchUrl, editUrl, idFieldName, title, columnNames, columnModel, method) {
    setupGridTable(grid_selector, pager_selector, searchUrl, editUrl, idFieldName, title, columnNames, columnModel, method, 30, '350px');
    setupGridPagerWithoutEdit(grid_selector, pager_selector, searchUrl, editUrl, idFieldName, title, columnNames, columnModel, method);
};
function setupGridWithHeight(grid_selector, pager_selector, searchUrl, editUrl, idFieldName, title, columnNames, columnModel, method, height) {
    setupGridTable(grid_selector, pager_selector, searchUrl, editUrl, idFieldName, title, columnNames, columnModel, method, 30, height);
    setupGridPagerWithoutEdit(grid_selector, pager_selector, searchUrl, editUrl, idFieldName, title, columnNames, columnModel, method);
};